<style lang="less" scoped>
.cf {
  zoom: 1;
}
.title_b_line {
    border-bottom: 1px solid #dbdbdb;
    padding: .2rem 0;
    margin-bottom: .266667rem;
}
.selector {
    border: 1px solid #ccc;
    border-radius: 3px;
    padding: 3px;
}
.selector i {
    font-size: 11px;
    zoom: 50%;
    display: inline-block;
    color: #888;
    transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -webkit-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    margin-right: 4px;
}
.list-btn {
     padding: .0rem; 
    text-align: right;
}
.list-btn .orders {
    color: #77babd;
    background: #ffffff;
    border-color: #77babd;
}
.list-btn .detail, .list-btn .refusal, .list-btn .orders {
    height: .52rem;
    line-height: .52rem;
    border-width: 1px;
    border-style: solid;
    border-radius: 4px;
    margin-left: .2rem;
    padding: 0 .2rem;
}
#ckCharts {
    margin: 0;
    min-height: 5rem;
    width: 100%;
}
.font-red {
    color: #F00220;
    font-size: 16px;
    padding: 0 3px;
}
</style>
 <!--接单业务单详情页-->
 <template>
   <div style="padding-bottom: 47px;">
    <app-head :show="showstate" :title="pagetitle"></app-head>
    <div class="car-bbinfo-card mb30" v-for="item in todolist">
      <div class="bbno lineb">业务单号：{{item.BBillNo}}</div>
      <div class="bbmain">
        <p class="displayflex"><i>制单时间</i><label class='flex1'>{{item.BillDate | time}}</label></p>
        <p class="displayflex"><i>供应单位</i><label class='flex1'>{{item.CargoOwnerName || '--'}}</label></p>
        <p class="displayflex"><i>销售单位</i><label class='flex1'>{{item.SaleCorpName  || '--'}}</label></p>
        <p class="displayflex"><i>送货地址</i><label class='flex1'>{{item.Address  || '--'}}</label></p>
        <p class="displayflex"><i>送货联系人</i><label class='flex1'>{{item.SendContacts || '--'}} {{item.SendContactsTel || '--'}}</label></p>
        <p class="displayflex" v-if="item.ADDT && item.ADDT != ''"><i>实际驶离时间</i><label class='flex1'>{{item.ADDT  || '--'}}</label></p> 
        <p class="displayflex"><i>总件数</i><label class='flex1 font-red'>{{item.Pkgs}}</label>件</p>
        <div v-if="lastTemp != '--'">
            <p class="displayflex" v-if="BillState*1 >= 52 && BillState*1 <= 56"><i>当前温度</i><label class='flex1 font-red'>{{lastTemp}}℃</label></p>
            <p class="displayflex" v-if="BillState === '81'"><i>签收温度</i><label class='flex1 font-red'>{{lastTemp}}℃</label></p>
        </div>
      </div>
    </div>
    <template>
        <div data class="car-bbinfo-card mb30">
          <div data class="bbmain lineb ">
            <div data class="vux-cell-box" v-on:click="shDepAddress()">
              <div class="weui-cell vux-tap-active weui-cell_access" v-for="eq in EquipList">
                <div class="weui-cell__hd">
                  <label class="weui-label" style="display: block; width: auto;">冷链设备</label>
                </div>
                <div class="vux-cell-primary vux-popup-picker-select-box">
                  <div class="vux-popup-picker-select" style="text-align: right;">
                    <span class="vux-popup-picker-placeholder vux-cell-placeholder">{{eq.Name}} (编号：{{eq.Code}})</span>
                  </div>
                </div>
                <div class="weui-cell__ft"></div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <actionsheet v-model="showDepAddress" :menus="depAddressLists" show-cancel :cancel-text="'关闭'">
        <p slot="header" v-html="tipD"></p>
      </actionsheet> 

      <div class="car-bbinfo-card mb30" > <!-- v-for="item in todolist" -->
          <div class="bbno lineb">温度记录图：<!-- {{item.BBillNo}} --></div>
          <div class="bbmain">
            <h3 class="title_b_line cf">
              <div style="float:left; height:.52rem; line-height:.52rem">
                <span class="selector" @click="chooseStarttime">
                  <i>▲</i>{{mtStarttime | dateFor}}</span> -
                <span class="selector" @click="chooseEndtime">
                  <i>▲</i>{{mtEndtime | dateFor}}</span>
                <mt-datetime-picker ref="picker1" v-model="mtStarttime" @confirm="handleConfirm1">
                </mt-datetime-picker>
                <mt-datetime-picker ref="picker2" v-model="mtEndtime" @confirm="handleConfirm2">
                </mt-datetime-picker>
              </div>
              <div class="list-btn" style="float:right"><input type="button" class="orders" style="margin-left:0" value="查询" @click="getSearchTemperatureRecordApiList"></div><!-- @click="getTempRecord('s', mtStarttime, mtEndtime)" -->
            </h3>
            <div class="chart-w" v-if="chartX.length > 0">  <!-- v-if="!chartShow" -->
                <div id="ckCharts" class="mrT10"></div>
              </div>

              <div class="noDate_page"  v-if="chartX.length == 0"  style="padding-top: 0;">  <!--  v-if="chartShow" -->
                <div class="noDate_icon">
                  <i class="iconfont icon-null"></i>
                </div>
                暂无温度数据！
              </div>
          </div>
      </div>
      <div class="car-bbinfo-card mb30" > <!-- v-for="item in todolist" -->
          <div class="bbno lineb">温度记录明细：<!-- {{item.BBillNo}} --></div>
          <div id="listbox" class="con_wldd_track">
            <ul id="listContent" class="track_dotRoute">
              <li v-for="(item,index) in tempdatas"> 
                <i></i>
                <div class="track_cont_detail">
                  <p>序号：{{totalRecords-index}}</p>
                  <p class="track_det_time">记录温度：{{item.Temperature}} ℃</p>
                  <p class="track_det_tit">时间：{{item.RecordTime}}</p>
                </div>
              </li>
            </ul>
            <div v-show="tempdatas.length > pageSize && tempdatas.length == totalRecords" style="text-align:center; padding:.266667rem 0; color:#888">没有更多数据了</div>
          </div>
          <div class="bbmain" v-show="totalRecords <= 0">
            <div class="noDate_page" style="padding-top: 0;">   
              <div class="noDate_icon"><i class="iconfont icon-null"></i></div>
              暂无温度数据！
            </div>
          </div>
      </div>
      <div class="form-btn">
        <div class="flex1" v-on:click="goToMiniApp()">打印冷链数据</div>
      </div>

 

    <!-- <footer-menu :status='2'></footer-menu> -->
  </div>
</template>
<script>
import echarts from "echarts";
import footerMenu from "@/components/core/footer/manage.footer.vue";
import appHead from '@/components/core/header/app_headbar.vue';
import uploader from '@/components/share/imageUploader/imageUploader.vue';

import { mapGetters, mapState } from 'vuex'

export default {
  components:{
    footerMenu,
    appHead,
    uploader,
  },
  data(){
    return{
      showDepAddress:false,
      depAddressList:'',
      depAddressLists:[],
      pickerValue: new Date(Date.parse(new Date) + 1000 * 60 * 60 * 24 * 1),
      mtStarttime:'2018/10/19 15:57:00',
      mtEndtime:'2018/10/19 16:57:59',
      startTimeSh:false,
      endTimeSh:false,
      dateVisible1: false,
      dateVisible2: false,
      todolist:[],
      EquipList:[],
      chartY: [],
      chartX: [],
      chartShow: false,
      lastTemp:'--',
      pageIndex:1,
      pageSize:10,
      tempdatas: [],
      sw: false,
      allLoaded: false,
      totalRecords:'',
      errorTemp: false,
      popupVisible:false,
      lastRec: {},
      BillState:0,
      // userVersion: this.$route.state.user.userVersion,


      OrderData:{
        Tratvehicleex:[],
      },
      ScrollerConfig: {
        content: "",
        downContent: "",
        height: 0,
        loadingContent: "",
        upContent: ""
      },
      Img52: [],
      Img56: [],
      Img81: [],
      mh:0,
    }
  },
  mounted(){
  },
  created(){
    this.getData();
  },
  computed: {
    tipD(){
      return `冷链设备<br><span class="actitle" style="font-size:16px">${this.depAddressList}</span>`;
    },
    ...mapState({
      pagetitle: state => state.cfg.appBarTitle,
      showstate: state => state.cfg.showAppBar,
    }),
    ...mapGetters({
      scrollerHeight: "cfg/getConHeight"
    }),
    userinfo(){
      return localStorage.userinfo?JSON.parse(localStorage.userinfo):null
    },
    inMini(){
      return window.__wxjs_environment === 'miniprogram';
    },
  },

  methods: {
    shDepAddress(){
      this.depAddressList = [];
      for (var i = 0; i < this.EquipList.length; i++) {
         var item = this.EquipList[i].Name+'（编号:'+ this.EquipList[i].Code+'）' 
      }
      this.depAddressList.push(item);
      this.showDepAddress = true;
    }, 
    getDtString(val) {
      var date;
      if (val instanceof Date) {
        date = val;
      } else {
        date = new Date(val.replace(/[\u4E00-\u9FA5]+/, "").replace("  ", " "));
      }

      let year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes();
      if (month < 9) {
        month = "0" + month;
      }
      if (day < 9) {
        day = "0" + day;
      }
      if (hour < 9) {
        hour = "0" + hour;
      }
      if (min < 9) {
        min = "0" + min;
      }
      return `${year}/${month}/${day} ${hour}:${min}`;
    },
    getDtString(val) {
      var date;
      if (val instanceof Date) {
        date = val;
      } else {
        date = new Date(val.replace(/[\u4E00-\u9FA5]+/, "").replace("  ", " "));
      }

      let year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes();
      if (month < 9) {
        month = "0" + month;
      }
      if (day < 9) {
        day = "0" + day;
      }
      if (hour < 9) {
        hour = "0" + hour;
      }
      if (min < 9) {
        min = "0" + min;
      }
      return `${year}/${month}/${day} ${hour}:${min}`;
    },
    chooseStarttime() {
      this.$refs.picker1.open();
    },
    chooseEndtime() {
      this.$refs.picker2.open();
    },
    handleConfirm1(pickerValue) {
      this.mtStarttime = this.getDtString(pickerValue);
      this.startTimeSh = true;
    },
    handleConfirm2(pickerValue) {
      this.mtEndtime = this.getDtString(pickerValue);
      this.endTimeSh = true;
    },
    getData: function() {
      var self = this,
          query = {
            id: JSON.parse(localStorage.userinfo).CorpGuid,
            billno: self.$route.query.BBillNo,
            EqpCode: '',
          };
      this.Ajax.post("SearchllOrderApi", query).then(function(resp) {
        if (resp.IsSuccess) {
          self.todolist = resp.Datas;
          self.getBillBindedEquipList();
          self.BillState = self.todolist[0].State;
        } else {
          self.Toast({
            message: "服务器异常"
          });
        }
      });
    },
    getBillBindedEquipList: function() {
      var self = this,
          query = {
            CorpGuid: JSON.parse(localStorage.userinfo).CorpGuid,
            BBillNo: self.$route.query.BBillNo,
            TenantGuid:self.todolist[0].TenantGuid,
          };
      this.Ajax.post("GetBillBindedEquip", query).then(function(resp) {
        if (resp.IsSuccess) {
          self.EquipList = resp.Datas;
          // self.BillState = self.todolist[0].State;
          self.getSearchTemperatureRecordApiList();
          self.getNext();
        } else {
          self.Toast({
            message: "服务器异常"
          });
        }
      });
    },
    getNext: function() {
      var self = this,
          query = {
            billno: self.$route.query.BBillNo,
            EqpCode:self.EquipList[0].Code,
          };
      this.Ajax.post("GetTemperatureSandEApi", query).then(function(resp) {
        if (resp.IsSuccess) {
          let res = resp.Datas;
          self.lastRec = res[1];
          self.lastTemp = self.lastRec.Temperature;
          // self.BillState = self.todolist[0].State;
        } else {
          self.Toast({
            message: "服务器异常"
          });
        }
      });
    },
    getSearchTemperatureRecordApiList: function() {
      var self = this,
          query = {
            PageIndex:1,
            PageSize: 999999,
            id: JSON.parse(localStorage.userinfo).CorpGuid,
            billno: self.$route.query.BBillNo,
            EqpCode:self.EquipList[0].EqpCode,
            starttime:this.getDtString(self.mtStarttime) + ':00',
            entime:this.getDtString(self.mtEndtime) + ':59'
          };
      this.Ajax.post("SearchTemperatureRecordApi", query).then(function(resp) {
        var valueX = [],
            valueY = [];
        if (resp.IsSuccess) {
          var result = resp.Datas;
          if (result && result.length > 0) {
            for (var a = 0; a < result.length; a++) {
              valueX.push(self.getDateAndTime(self.getDtString(result[a]["RecordTime"])));
              valueY.push(result[a]["Temperature"].toFixed(1));
            }
            self.chartX = valueX;
            self.chartY = valueY;

            self.getGoodsTemp();

            self.lastTemp = result[0]["Temperature"].toFixed(1);
            let width = 100;
            if (self.chartX.length > 50) {
              width = 2 * self.chartX.length;
            }
            // document.getElementById("ckCharts").style.width = width + "%";
            self.getTotalTempRecord();
            setTimeout(function () {
                self.showChart();
            }, 1500);
            
          }
          // self.BillState = self.todolist[0].State;
        } else {
          self.Toast({
            message: "服务器异常"
          });
        }
      });
    },
    getGoodsTemp(){
      var self = this,
      query = {
        CorpGuid: JSON.parse(localStorage.userinfo).CorpGuid,
        TenantGuid: JSON.parse(localStorage.userinfo).TenantGUID,
        BBillNo: self.$route.query.BBillNo,
      };
      this.Ajax.post("GetGoodsTempMaxAndMin", query).then((resp) => {
        if(resp.IsSuccess) {
          var datas = resp.Datas;
          datas.forEach((x) => {
            if(self.lastTemp*1 > x.TemperatureMaxValue*1 || self.lastTemp*1 < x.TemperatureMinValue*1){
              self.errorTemp = true;
            }
          })
        } else {
          this.Toast({
            message: "服务器异常"
          });
        }
      });
    },
    getTotalTempRecord: function() {
      var self = this,
          query = {
            PageIndex:1,
            PageSize: this.pageSize,
            id: JSON.parse(localStorage.userinfo).CorpGuid,
            billno: self.$route.query.BBillNo,
            EqpCode:self.EquipList[0].EqpCode,
            starttime:this.getDtString(self.mtStarttime) + ':00',
            entime:this.getDtString(self.mtEndtime) + ':59'
          };
      this.Ajax.post("SearchTemperatureRecordApi", query).then(function(resp) {
        let datas = [];
        if (resp.IsSuccess) {
          self.totalRecords = resp.TotalRecords;

          var result = resp.Datas;
          if (result && result.length > 0) {
            for (var a = 0; a < result.length; a++) {
              var Record = {
                RecordTime : self.getDtString(result[a]["RecordTime"]),
                Temperature : result[a].Temperature,
              }
              datas.push(Record);
            }
            self.tempdatas = self.tempdatas.concat(datas);
            console.log(self.tempdatas);
            if(self.tempdatas.length < resp.TotalRecords) {
              self.pageIndex++;
              self.sw = true;
            } else {
              self.allLoaded = true;
              self.sw = false;
            }
          } else {
            self.sw = false;
          }
        } else {
          self.Toast({
            message: "服务器异常"
          });
        }
      });
    },
    getDateAndTime(dt){
      let date = new Date(dt),
          month = getTwo(date.getMonth() + 1),
          day = getTwo(date.getDate()),
          hour = getTwo(date.getHours()),
          min = getTwo(date.getMinutes());

      function getTwo(str){
        if(str * 1 < 10) {
          return  '0'+str;
        } else {
          return str
        }
      }
      return `${month}/${day} ${hour}:${min}`;
    },
  showChart() {
      var self = this;
      var myChart = echarts.init(document.getElementById("ckCharts"));
      myChart.resize();
      var option = {
        baseOption: {
          title: {
            show:false,
            // text: "",
            // textStyle: {
            //   fontSize: 14,
            //   color: "#696969"
            // },
            // x: "right",
            // y: 0,
          },
          tooltip: {
            backgroundColor: "rgba(100,159,163,1)",
            formatter: "{b}<br>{c} ℃"
          },
          grid: {
            top:"15%",
            left:34,
            right:0,
            containLabel: true
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: self.chartX,
            inverse:true,
            // axisLine: {
            //   show: true,
            //   lineStyle: {
            //       color: '#888',
            //       type: 'solid',
            //   },
            // },
            axisLabel: {
              showMinLabel: true,
              showMaxLabel: true,
              // interval: 10,
              // formatter: function(value, index) {
              //   return value.replace(' ', '\n');
              // }
            }
          },
          yAxis: {
            type: "value",
            position:'right',
            axisLabel: {
              formatter: "{value} °C"
            },
            axisLine: {
              show: true,
              lineStyle: {
                  color: '#888',
                  type: 'solid',
              },
            },
            splitLine: {
              lineStyle: {
                color: '#ccc',
                type: 'dotted',
              }
            }
          },
          series: [
            {
              type: "line",
              smooth:true,
              symbol: 'emptyCircle',
              symbolSize: 4,
              showSymbol: false,
              name: "温度",
              itemStyle: {
                normal: {
                  color: 'rgba(109, 179, 205,0.8)'
                }
              },
              markPoint: {
                symbol:'pin',
                symbolSize:50,
                symbolRotate:0,
                data: [
                  {type: 'max', name: '最大值'},
                  {type: 'min', name: '最小值'}
                ],
              },
              lineStyle: {
                normal: {
                  color: '#6194c9', //连线颜色
                  width: 1.5,
                }
              },
              areaStyle: {
                normal: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                      offset: 0,
                      color: 'rgba(74,140,180,0.3)'
                  }, {
                      offset: 0.8,
                      color: 'rgba(148,206,241,0.3)'
                  }], false),
                  shadowColor: 'rgba(242,255,255,0.8)',
                  shadowBlur: 10
                }
              },
              data: self.chartY,
            }
          ],
          dataZoom: [{
              start: '0'
          }, {
              type: 'inside'
          }]
        }
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.clear();
      myChart.setOption(option);
      let distance = $('.chart-w').outerWidth(),
          ele = $('.chart-w');
      ele.scrollLeft(distance * 100);
      // $("#ckCharts").removeAttr("_echarts_instance_");
    },
     goToMiniApp(){
      let self = this;
      if(this.inMini) {
        let billno = self.$route.query.BBillNo,
            id = JSON.parse(localStorage.userinfo).CorpGuid,
            entime = self.getDtString(self.mtEndtime),
            starttime = self.getDtString(self.mtStarttime),
            route = self.$route.path.split('/')[1],
            billguid = JSON.parse(localStorage.userinfo).CorpGuid,
            EqpCode = self.EquipList[0].Code,
            EqpName = self.EquipList[0].Name,
            errorTemp = this.errorTemp?'Y':'N',
            url = `/pages/getTempRecord/getTempRecord?route=${route}&billguid=${billguid}&billno=${billno}&EqpCode=${EqpCode}&EqpName=${EqpName}&id=${id}&entime=${entime}&starttime=${starttime}&errorTemp=${errorTemp}&userVersion=${this.userVersion}`;
            console.log(url);
        wx.miniProgram.navigateTo({
          url: url,
        })

      } else {
        self.Toast({
          message: "请在微信小程序内使用单据打印功能",
          duration:5000,
        });
      }
    },
  },
 filters: {
    dateFor(val) { 
      var date;
      if (val instanceof Date) {
        date = val;
      } else {
        date = new Date(val.replace(/[\u4E00-\u9FA5]+/, "").replace("  ", " "));
      }

      let year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes();
      if (month < 9) {
        month = "0" + month;
      }
      if (day < 9) {
        day = "0" + day;
      }
      if (hour < 9) {
        hour = "0" + hour;
      }
      if (min < 9) {
        min = "0" + min;
      }
      return `${year}/${month}/${day} ${hour}:${min}`;
    },
    time(val) { 
      var date;
      if (val instanceof Date) {
        date = val;
      } else {
        date = new Date(val.replace(/[\u4E00-\u9FA5]+/, "").replace("  ", " "));
      }

      let year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes();
      if (month < 9) {
        month = "0" + month;
      }
      if (day < 9) {
        day = "0" + day;
      }
      if (hour < 9) {
        hour = "0" + hour;
      }
      if (min < 9) {
        min = "0" + min;
      }
      return `${year}/${month}/${day}`;
    }
  },
}
</script>

